package shop.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBUtil {

	static Connection conn = null;
	static PreparedStatement ps = null;
	static ResultSet rs = null;

	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/interesting_shop_db?characterEncoding=utf-8", "root", "admin");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 执行查询
	public static ResultSet query(String sql,Object[] params) {
		try {
			if(conn==null) {
				getConnection();
			}
			ps = conn.prepareStatement(sql);
			if(params!=null) {
				for(int i = 0;i<params.length;i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			System.out.println(sql);
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 执行更新
	public static void update(String sql,Object[] params) {
		try {
			if(conn==null) {
				getConnection();
			}
			ps = conn.prepareStatement(sql);
			if(params!=null) {
				for(int i = 0;i<params.length;i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			System.out.println(sql);
			ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
